<?php


namespace app\backstage\server;


use app\common\model\Novel;
use app\common\model\NovelChapter;

class NovelServer
{
    /**
     * 章节续传和覆盖
     * @param Novel $novel
     * @param $type
     * @param $novelFileContent
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function batchAddChapter(Novel $novel, $type, $novelFileContent)
    {
        if ($type == 1) {
            //续传
            $fastNo = NovelChapter::where('novel_id', $novel->id)->max('chapter_no');
        } else {
            //覆盖
            $fastNo = 0;
        }
        $where[] = ['novel_id', '=', $novel->id];
        $where[] = ['is_pay', '=', 1];
        $fastPayNo = NovelChapter::where($where)->min('chapter_no');
        $fastPayNo = $fastPayNo ? $fastPayNo : 7;
        $i = 1;
        foreach ($novelFileContent['data']['chapters'] as $k => $v) {
            if ($i > $fastNo) {
                $where = [];
                $where[] = ['novel_id', '=', $novel->id];
                $where[] = ['chapter_no', '=', $i];
                $chapterModel = NovelChapter::where($where)->find();
                if (!$chapterModel) {
                    $chapterModel = new NovelChapter;
                }
                $chapterModel->novel_id = $novel->id;
                $chapterModel->name = $v['cname'];
                $chapterModel->chapter_no = $i;
                $chapterModel->is_pay = $i >= $fastPayNo ? 1 : 0;
                $chapterModel->words = clearHtmlGetNum($v['content']);;
                $chapterModel->setContent(formatChapterContent($v['content'],"","\n"), $novel->id, $i);
                $chapterModel->save();
            }
            $i++;
        }
        $novel->number_words = NovelChapter::where("novel_id", $novel->id)->sum('words');
        $novel->chapter_up_time = date("Y-m-d H:i:s");
        $novel->save();
        return ['code' => 0, 'msg' => '章节添加成功'];
    }
}